<!-- 修改密码 -->
<template>
  <h2 style="color: #595959; margin-bottom: 20px">
    {{ $t("messages.ChangePassword") }}
  </h2>
  <el-form
    :rules="formRules"
    :model="form"
    ref="formRef"
    label-width="100px"
    class="form-container"
  >
    <!-- 原密码 -->
    <el-form-item label="原密码" prop="oldPassword">
      <el-input
        v-model="form.oldPassword"
        type="password"
        placeholder="请输入原密码"
        :rules="passwordRules"
        @blur="checkOldPasswordInp"
      />
      <!-- <span
        v-if="oldPasswordMessage.message"
        :style="{ color: oldPasswordMessage.isValid ? 'green' : 'red' }"
      >
        {{ oldPasswordMessage.message }}
      </span> -->
    </el-form-item>

    <!-- 新密码 -->
    <el-form-item label="新密码" prop="newPassword">
      <el-input
        v-model="form.newPassword"
        type="password"
        placeholder="请输入新密码"
        :rules="passwordRules"
      />
    </el-form-item>

    <!-- 确认新密码 -->
    <el-form-item label="确认新密码" prop="confirmPassword">
      <el-input
        v-model="form.confirmPassword"
        type="password"
        placeholder="请确认新密码"
        :rules="confirmPasswordRules"
      />
    </el-form-item>

    <!-- 确定按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from "element-plus";
import { checkOldPassword, editPassword } from "@/api/index.js";
const formRef = ref(null);
const form = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
const oldPasswordCheck = ref(false);

const router = useRouter();
// 表单验证规则
const formRules = ref({
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { validator: oldPasswordValidator, trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      validator: confirmNewPassword,
      min: 6,
      max: 16,
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { validator: confirmPasswordValidator, trigger: "blur" },
  ],
});

function confirmNewPassword(rule, value, callback) {
  if (value === form.value.oldPassword) {
    return callback(new Error("新密码与旧密码一致"));
  }
  callback(); // 验证通过
}

// 修改 oldPasswordValidator，先调用异步方法再验证
function oldPasswordValidator(rule, value, callback) {
  // 调用异步验证，检查旧密码是否正确
  checkOldPasswordInp()
    .then(() => {
      if (!oldPasswordCheck.value) {
        return callback(new Error("原密码不正确"));
      }
      callback(); // 验证通过
    })
    .catch(() => {
      callback(new Error("检查旧密码失败，请稍后再试"));
    });
}

// 确认密码自定义验证
function confirmPasswordValidator(rule, value, callback) {
  if (value !== form.value.newPassword) {
    return callback(new Error("新密码和确认新密码不一致"));
  }
  callback(); // 验证通过
}
// 检查旧密码是否正确
const checkOldPasswordInp = async () => {
  const res = await checkOldPassword({ oldPwd: form.value.oldPassword });
  console.log("🚀 ~ checkOldPassword ~ res:", res);
  if (res.code === "00") {
    oldPasswordCheck.value = true;
  } else {
    oldPasswordCheck.value = false;
  }
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 提交表单逻辑
      console.log("表单提交:", form.value);
      const res = await editPassword({
        newPwd: form.value.confirmPassword,
      });
      console.log(res);

      if (res.code === 9999) {
        ElMessage.warning("你的力量不足以修改管理员密码哦！");
      } else if (res.code === 0) {
        ElMessage.success("修改密码成功，三秒后将跳回首页，请重新登录");
        setTimeout(() => {
          router.push("/login");
        }, 3000);
      } else {
        ElMessage.error("修改密码失败");
      }
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};
</script>

<style scoped>
.form-container {
  width: 80%;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
